class PostsController < ApplicationController
  before_filter :load_resources, :except => [:index]

  def edit
    @post = @topic.posts.find(params[:id])
  end
  
  def create
    @post = @topic.posts.build(params[:post])
    @post.user_id = current_user.id
    
    respond_to do |format|
      if @post.save
        flash[:notice] = _('Post was successfully created')
        format.html { redirect_to forum_topic_path(@forum, @topic) }
        format.xml  { head :created, :location => forum_topic_path(@forum, @topic) }
      else
        format.html { render :action => :new }
        format.xml  { render :xml => @topic.errors.to_xml }
      end
    end
  end

  def update
    @post = @topic.posts.find(params[:id])
    new_attributes = params[:post].except(:user_id, :topic_id)
    new_attributes.merge(:updated_by => current_user.id) if current_user.id != @post.user_id
    
    respond_to do |format|
      if @post.update_attributes(new_attributes)
        flash[:notice] = _('Post was successfully updated')
        format.html { redirect_to forum_topic_path(@forum, @topic) }
        format.xml  { head :ok, :location => forum_topic_path(@forum, @topic) }
      else
        format.html { render :action => :new }
        format.xml  { render :xml => @topic.errors.to_xml }
      end
    end
  end
  
  private
  def load_resources
    @topic = Topic.find(params[:topic_id],
      :select => 'topics.id, topics.title, topics.permalink',
      :include => [:forum[:id, :name, :permalink] => :category[:name]])
    @forum = @topic.forum
    @category = @forum.category
  rescue ActiveRecord::RecordNotFound
    flash[:error] = _('Topic not found')
    redirect_back_or(forum_path(params[:forum_id]))
  end
end
